package com.xiao.mall.foundation.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.utils.IOUtils;
import com.xiao.mall.foundation.config.TencentCosProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Base64;

/**
 * @author zhoushaofeng
 */
@Component
@Slf4j
public class TecentCosService {
    private final TencentCosProperties cosProperties;

    public TecentCosService(TencentCosProperties cosProperties) {
        this.cosProperties = cosProperties;
    }

    public byte[] downloadImage(String url) {
        //存储桶文件夹
        final String removeHttpUrl = url.replace("http://", "").replace("https://", "");
        final String fileKey = removeHttpUrl.substring(removeHttpUrl.indexOf("/"));

        COSCredentials cred = new BasicCOSCredentials(cosProperties.getSecretId(), cosProperties.getSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region(cosProperties.getRegion()));
        COSClient cosclient = new COSClient(cred, clientConfig);

        try {

            GetObjectRequest request = new GetObjectRequest(cosProperties.getBucketKey(),
                    URLDecoder.decode(fileKey, "UTF-8"));

            COSObject object = cosclient.getObject(request);
            return IOUtils.toByteArray(object.getObjectContent());
        } catch (CosServiceException | IOException e) {
            log.error("获取Cos资源{}失败！{}", url, e);
            throw new RuntimeException(e);
        } finally {
            cosclient.shutdown();
        }
    }

    public String downloadImageAsBase64(String url) {
        final String fileName = url.substring(url.lastIndexOf("/") + 1);
        final String prefix = fileName.lastIndexOf(".") >= 0 ?
                String.format("data:image/%s;base64,", fileName.substring(fileName.lastIndexOf(".") + 1)) :
                "base64,";
        return prefix + Base64.getEncoder().encodeToString(downloadImage(url));
    }
}
